package ltd.dujiabao.msmservice.controller;

import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.commonutils.Result;
import ltd.dujiabao.commonutils.ResultCode;
import ltd.dujiabao.msmservice.service.MsmService;
import ltd.dujiabao.commonutils.RandomUtil;
import ltd.dujiabao.servicebase.exception.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author : DuJiabao
 * @Project : online-course-project
 * @Time : 2021/4/24 14:43
 * @Desc :
 */
@RestController
@RequestMapping("/msm")
@CrossOrigin //跨域
@Slf4j
public class MsmController {
  @Autowired
  private MsmService msmService;

  @Autowired
  RedisTemplate<String, String> redisTemplate;

  /**
   * 会通过redis缓存电话号码的验证码，用于用户验证。
   *
   * @param phone
   * @return
   */
  @GetMapping(value = "/code/{phone}")
  public Result code(@PathVariable String phone) {
    if (StringUtils.isEmpty(phone)) {
      log.error("电话号码错误");
      throw new MyException(ResultCode.FAILURE, "电话号码错误");
    }

    // 如果找到了，那就直接返回ok就好了，不需要再发了
    String code = redisTemplate.opsForValue().get(phone);
    if (!StringUtils.isEmpty(code)) {
      log.info("在redis中找到了该电话号码，直接返回成功");
      return Result.success();
    }

    //   否则，自己生成一个四位数的随机码，发短信给用户
    code = RandomUtil.getFourBitRandom();
    Map<String, Object> param = new HashMap<>();
    param.put("code", code);
    boolean isSuccess = msmService.send(phone, "SMS_180051135", param);
    if (isSuccess) {
      redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES); // 将验证码暂时存放在redis中，并限制生命周期为5min
      log.info("成功发送短信给" + phone + "，验证码为 " + code);
      return Result.success();
    } else {
      throw new MyException(ResultCode.FAILURE, "发送短信失败");
    }
  }
}
